/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.compass.gps;

import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;


// Simple location polling thread. One could use the listener built into the locationprovider, but we
// didn't get the location as fast as with this simple self-made thread.
public class LocationFinder extends Thread {

    private Criteria criteria;
    private LocationListener listener;
    private boolean running = false;
    private LocationProvider lp = null;
    public LocationFinder(LocationListener listener) {
        this.listener = listener;
        criteria = new Criteria();
        criteria.setCostAllowed(true);
        criteria.setPreferredPowerConsumption(criteria.NO_REQUIREMENT);
        criteria.setSpeedAndCourseRequired(true);
    }

    public void run() {
        running = true;
        
        try {
            lp = LocationProvider.getInstance(criteria);
        }catch(LocationException le) {
            System.out.println("LOCATION ERROR:" + le.getMessage());
            running = false;
        }
        
        while (running) {
            try {
                System.out.println("polling location");
                
                Location lc = lp.getLocation(60);
                listener.locationReceived(lc);
                /**
                 * this for theoretical situation where location is immediately received.
                 * which would cause constant location polling and that would eat all the memory.
                 */
                this.sleep(20000);
            } catch (LocationException le) {
                System.out.println("LOCATION ERROR:" + le.toString());
            } catch (InterruptedException ie) {
                System.out.println("INTERRUPTED ERROR:" + ie.getMessage());
                running = false;
            }
        }
    }
    public void quit() {
        running = false;
        if(lp != null) {
            lp.reset();
        }
    }
}
